import time
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
from flask import Flask

class FileChangeHandler(FileSystemEventHandler):
    def __init__(self, app: Flask):
        self.app = app
        self.last_reload = time.time()
        self.reload_delay = 1  # Minimum seconds between reloads

    def on_modified(self, event):
        if event.is_directory:
            return
            
        current_time = time.time()
        if current_time - self.last_reload > self.reload_delay:
            print(f"File {event.src_path} has been modified")
            self.last_reload = current_time
            with self.app.app_context():
                # You can add custom reload logic here if needed
                pass

def setup_file_watcher(app: Flask, watch_path: str):
    event_handler = FileChangeHandler(app)
    observer = Observer()
    observer.schedule(event_handler, watch_path, recursive=True)
    observer.start()
    return observer
